//
//  ToolImageCutViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "ToolImageCutViewController.h"
#import "PointsSpreadView.h"
#import "CustomContentView.h"
#import "CustomAlertView.h"
#import "UIImage+TExtension.h"
#import "GPUImage.h"
#import "ToolImageScanViewController.h"
#import "LineCorverageView.h"

@interface ToolImageCutViewController () {
    NSMutableArray  *pointViewMutArr;
    NSMutableArray  *contentViewMutArr;
    NSInteger       currentPage;
}
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *againBtn;
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;

@property (nonatomic,assign) CGRect         contentRect;
@property (nonatomic,weak) UIImageView      *showImageView;

@end

@implementation ToolImageCutViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.isEdit) {
        self.title = self.titleStr;
    } else {
        //@[0@"万物识别图",1@"证件扫描",2@"拍图识字",3@"文档扫描",4@"图片转word",5@"表格识别"]
        if (self.selectIndex == 5) {
            self.title = @"表格识别";
        } else {
            self.title = @"图片扫描";
        }
    }
    
    [self addBackBtn];
    
    pointViewMutArr = [NSMutableArray array];
    contentViewMutArr = [NSMutableArray array];
    
    [self initView];
    [self showImage];
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.fd_interactivePopDisabled = YES;
}

- (IBAction)fullPress {
    PointsSpreadView *pointView = [pointViewMutArr objectAtIndex:currentPage];
    [pointView resetPoint];
}
- (IBAction)leftPress {
    CustomContentView *contentView = [contentViewMutArr objectAtIndex:currentPage];
    [contentView actionLeftRotate];
}

- (IBAction)rightPress {
    CustomContentView *contentView = [contentViewMutArr objectAtIndex:currentPage];
    [contentView actionRightRotate];
}

- (IBAction)savePress{
    [self changeImage];
    if (self.SaveHandle) {
        self.SaveHandle(self.image);
    }
    [self goBackAction];
}

- (void)showImage {
    CGRect loadingFrame;
    UIImage *image = self.image;
    CustomContentView *contentView = [[CustomContentView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH_DEVICE, self.scrollView.frame.size.height)];
     if (image.size.width > image.size.height) {
         contentView.horizontal = YES;
     }
    [contentView setBackgroundColor:ViewBackgroundColor];
    float width = image.size.width;
    float height = image.size.height;
    float originX = 0;
    float originY = 0;
    float margin = 40;
    if (height > width) {
        originY = margin;
        height = contentView.frame.size.height - margin*2;
        width = floorf((image.size.width/image.size.height)*height);
        originX = floorf((contentView.frame.size.width - width)/2.0);
    } else {
        originX = margin;
        width = contentView.frame.size.width - margin*2;
        height = floorf((image.size.height/image.size.width)*width);
        originY = floorf((contentView.frame.size.height - height)/2.0);
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(originX, originY, width, height)];
    imageView.image = image;
     imageView.contentMode = UIViewContentModeScaleAspectFill;
    [contentView addSubview:imageView];
    self.showImageView = imageView;
    loadingFrame = imageView.frame;
    
    //扫描动画
    UIImageView *loading = [[UIImageView alloc] initWithFrame:CGRectMake(loadingFrame.origin.x, loadingFrame.origin.y, loadingFrame.size.width, (194.0/652)*loadingFrame.size.width)];
    [loading setImage:[UIImage imageNamed:@"scan"]];
    [contentView addSubview:loading];
    [UIView animateWithDuration:2.0f animations:^{
        [loading setFrame:CGRectMake(loadingFrame.origin.x, loadingFrame.size.height+loadingFrame.origin.y-loading.frame.size.height, loadingFrame.size.width, loading.frame.size.height)];
        loading.alpha = 0.3;
    } completion:^(BOOL finished) {
        [loading removeFromSuperview];
    }];
     
     self.contentRect = imageView.frame;
    
    PointsSpreadView *pointView = [[PointsSpreadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH_DEVICE, self.scrollView.frame.size.height)];
     pointView.contentView = contentView;
    [contentView addSubview:pointView];
     
     
     CIImage *ciImage = [[CIImage alloc] initWithImage:image];
     UIColor *mainColor = [UIImage mainColorOfImage:image];
     if (![self isLightColor:mainColor]) {
         ciImage = [[CIImage alloc] initWithImage:[self imageByContrastFilter:image]];//暗色图片增加对比度后检测矩形效果更好
     }
     
     CIDetector *detector = [self highAccuracyRectangleDetector];
     NSArray *rectangles = [detector featuresInImage:ciImage options:@{CIDetectorImageOrientation : @(image.imageOrientation)}];
     if (rectangles.count > 0) {
         IPDFRectangleFeature *detectionFeature = [[IPDFRectangleFeature alloc] initWithFeature:[self coordinateTransformWithCIRectangleFeature:rectangles.firstObject ciImage:ciImage]];
         [pointView.coverageView addPointWithCGPoint:detectionFeature.topLeft];
         [pointView.coverageView addPointWithCGPoint:detectionFeature.bottomLeft];
         [pointView.coverageView addPointWithCGPoint:detectionFeature.bottomRight];
         [pointView.coverageView addPointWithCGPoint:detectionFeature.topRight];
     } else {
         [pointView.coverageView addPointWithCGPoint:CGPointMake(originX, originY)];
         [pointView.coverageView addPointWithCGPoint:CGPointMake(originX, height+originY)];
         [pointView.coverageView addPointWithCGPoint:CGPointMake(width+originX, height+originY)];
         [pointView.coverageView addPointWithCGPoint:CGPointMake(width+originX, originY)];
     }
             
    [pointView.coverageView handleMidpoint];
    pointView.maxRect = imageView.frame;
    pointView.coverageView.maxRect = imageView.frame;
    
    [pointViewMutArr addObject:pointView];
    [contentViewMutArr addObject:contentView];
    
    [self.scrollView addSubview:contentView];
    [self.scrollView setContentSize:CGSizeMake(0, 0)];

}

//改变图片区域
- (void)changeImage {
    UIImageView *imageView = self.showImageView;
    PointsSpreadView *rectView = [pointViewMutArr objectAtIndex:0];
    MNPoint *point0 = [rectView.coverageView.pointsArray objectAtIndex:0];
    MNPoint *point1 = [rectView.coverageView.pointsArray objectAtIndex:1];
    MNPoint *point2 = [rectView.coverageView.pointsArray objectAtIndex:2];
    MNPoint *point3 = [rectView.coverageView.pointsArray objectAtIndex:3];
    
    IPDFRectangleFeature *transformFeature = [[IPDFRectangleFeature alloc] init];
    transformFeature.topLeft = CGPointMake(point0.x-imageView.frame.origin.x, point0.y-imageView.frame.origin.y);
    transformFeature.topRight = CGPointMake(point3.x-imageView.frame.origin.x, point3.y-imageView.frame.origin.y);
    transformFeature.bottomLeft = CGPointMake(point1.x-imageView.frame.origin.x, point1.y-imageView.frame.origin.y);
    transformFeature.bottomRight = CGPointMake(point2.x-imageView.frame.origin.x, point2.y-imageView.frame.origin.y);
    
    CIImage *ciimage = [[CIImage alloc] initWithImage:imageView.image];
    CIRectangleFeature *feature = [self coordinateTransformWithIPDFRectangleFeature:transformFeature ciImage:ciimage];
    UIImage *clipImage = [self correctPerspectiveForImage:ciimage withFeatures:feature];
    self.image = clipImage;
}


//截取矩形框内的图片并返回
- (UIImage *)correctPerspectiveForImage:(CIImage *)ciimage withFeatures:(CIRectangleFeature *)rectangleFeature {
    //矩形矫正
    NSMutableDictionary *rectangleCoordinates = [[NSMutableDictionary alloc] initWithCapacity:4];
    rectangleCoordinates[@"inputTopLeft"] = [CIVector vectorWithCGPoint:rectangleFeature.topLeft];
    rectangleCoordinates[@"inputTopRight"] = [CIVector vectorWithCGPoint:rectangleFeature.topRight];
    rectangleCoordinates[@"inputBottomLeft"] = [CIVector vectorWithCGPoint:rectangleFeature.bottomLeft];
    rectangleCoordinates[@"inputBottomRight"] = [CIVector vectorWithCGPoint:rectangleFeature.bottomRight];
    ciimage = [ciimage imageByApplyingFilter:@"CIPerspectiveCorrection" withInputParameters:rectangleCoordinates];

    static CIContext *ctx = nil;
    if (!ctx) {
        ctx = [CIContext contextWithOptions:@{kCIContextWorkingColorSpace:[NSNull null]}];
    }

    CGImageRef imageRef = [ctx createCGImage:ciimage fromRect:ciimage.extent];
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    CFRelease(imageRef);
    
    return returnImage;
    
}


//转换为图片的坐标 截取图片
- (CIRectangleFeature *)coordinateTransformWithIPDFRectangleFeature:(IPDFRectangleFeature *)feature ciImage:(CIImage *)ciImage {
    CGSize imageSize = ciImage.extent.size;
    CGSize containerSize = self.contentRect.size;
    CGFloat scale = MAX(imageSize.width / containerSize.width, imageSize.height / containerSize.height);
    //remove margin
    CGAffineTransform transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 0);
    CGPoint topLeft = CGPointApplyAffineTransform(feature.topLeft, transform);
    CGPoint topRight = CGPointApplyAffineTransform(feature.topRight, transform);
    CGPoint bottomRight = CGPointApplyAffineTransform(feature.bottomRight, transform);
    CGPoint bottomLeft = CGPointApplyAffineTransform(feature.bottomLeft, transform);
    //rotate coordinate-Y + offset
    CGFloat off_x = (containerSize.width - imageSize.width / scale) / 2;
    CGFloat off_y = (containerSize.height - imageSize.height / scale) / 2;
    topLeft = CGPointMake(topLeft.x - off_x, containerSize.height - topLeft.y - off_y);
    topRight = CGPointMake(topRight.x - off_x, containerSize.height - topRight.y - off_y);
    bottomRight = CGPointMake(bottomRight.x - off_x, containerSize.height - bottomRight.y - off_y);
    bottomLeft = CGPointMake(bottomLeft.x - off_x, containerSize.height - bottomLeft.y - off_y);
    //scale
    transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
    topLeft = CGPointApplyAffineTransform(topLeft, transform);
    topRight = CGPointApplyAffineTransform(topRight, transform);
    bottomLeft = CGPointApplyAffineTransform(bottomLeft, transform);
    bottomRight = CGPointApplyAffineTransform(bottomRight, transform);
    IPDFRectangleFeature *transformFeature = [[IPDFRectangleFeature alloc] init];
    transformFeature.topLeft = topLeft;
    transformFeature.topRight = topRight;
    transformFeature.bottomRight = bottomRight;
    transformFeature.bottomLeft = bottomLeft;
    return (CIRectangleFeature *)transformFeature;
}

- (void)initView {
    [self.view setBackgroundColor:ViewBackgroundColor];
    [self.bottomView setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - 76 - IS_iPhoneX_Bottom, SCREEN_WIDTH_DEVICE, 76 + IS_iPhoneX_Bottom)];
    addShadowToView(self.saveBtn, 0.3, 8, 17.0f);
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Top - NavBarHeight - self.bottomView.frame.size.height)];

    self.changeBtn.hidden = !self.isEdit;
    self.againBtn.hidden = self.isEdit;
    self.scrollView.scrollEnabled = !self.isEdit;
}

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // 得到每页宽度
    CGFloat pageWidth = sender.frame.size.width;
    // 根据当前的x坐标和页宽度计算出当前页数
    currentPage = floor((sender.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"====当前页:%ld", currentPage);
}

//判断颜色是不是亮色
- (BOOL) isLightColor:(UIColor *)color {
    CGFloat components[3];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char resultingPixel[4];
    CGContextRef context = CGBitmapContextCreate(&resultingPixel,
                                                 1,
                                                 1,
                                                 8,
                                                 4,
                                                 rgbColorSpace,
                                                 bitmapInfo);
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorSpace);
    
    for (int component = 0; component < 3; component++) {
        components[component] = resultingPixel[component];
    }
    
    
    
    CGFloat num = components[0] + components[1] + components[2];
    if(num < 250) {
        return NO;
    }
    else {
        return YES;
    }
}

#pragma mark ===== 滤镜 ====

- (UIImage *)imageByContrastFilter:(UIImage *)image {
    //对比度 (0 - 4)
    GPUImageContrastFilter *contrastFilter = [[GPUImageContrastFilter alloc] init];
    contrastFilter.contrast = 3.0;
    return [contrastFilter imageByFilteringImage:image];
}

//检测器
- (CIDetector *)highAccuracyRectangleDetector {
    static CIDetector *detector = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^ {
        detector = [CIDetector detectorOfType:CIDetectorTypeRectangle
                                      context:nil
                                      options:@{
                                                CIDetectorAccuracy : CIDetectorAccuracyHigh,
                                                CIDetectorImageOrientation:@(0),
                                                }];
    });
    return detector;
}

//转换为self.view的坐标
- (IPDFRectangleFeature *)coordinateTransformWithCIRectangleFeature:(CIRectangleFeature *)feature ciImage:(CIImage *)ciImage {
    
    CGSize imageSize = ciImage.extent.size;
    CGSize containerSize = self.contentRect.size;

    CGFloat scale = MAX(imageSize.width / containerSize.width, imageSize.height / containerSize.height);

    //scale
    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, 1/scale, 1/scale);
    CGPoint topLeft = CGPointApplyAffineTransform(feature.topLeft, transform);
    CGPoint topRight = CGPointApplyAffineTransform(feature.topRight, transform);
    CGPoint bottomLeft = CGPointApplyAffineTransform(feature.bottomLeft, transform);
    CGPoint bottomRight = CGPointApplyAffineTransform(feature.bottomRight, transform);

    //rotate coordinate-Y + offset
    CGFloat off_x = (containerSize.width - imageSize.width / scale) / 2;
    CGFloat off_y = (containerSize.height - imageSize.height / scale) / 2;

    topLeft = CGPointMake(topLeft.x + off_x, containerSize.height - topLeft.y - off_y);
    topRight = CGPointMake(topRight.x + off_x, containerSize.height - topRight.y - off_y);
    bottomRight = CGPointMake(bottomRight.x + off_x, containerSize.height - bottomRight.y - off_y);
    bottomLeft = CGPointMake(bottomLeft.x + off_x, containerSize.height - bottomLeft.y - off_y);

    //margin
    transform = CGAffineTransformTranslate(CGAffineTransformIdentity, self.contentRect.origin.x, self.contentRect.origin.y);
    topLeft = CGPointApplyAffineTransform(topLeft, transform);
    topRight = CGPointApplyAffineTransform(topRight, transform);
    bottomRight = CGPointApplyAffineTransform(bottomRight, transform);
    bottomLeft = CGPointApplyAffineTransform(bottomLeft, transform);
    
    IPDFRectangleFeature *transformFeature = [[IPDFRectangleFeature alloc] init];
    transformFeature.topLeft = topLeft;
    transformFeature.topRight = topRight;
    transformFeature.bottomLeft = bottomLeft;
    transformFeature.bottomRight = bottomRight;
    
    return transformFeature;
}
@end
